package com.jumper.study.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.jumper.study.common.captcha.ICaptchaStore;

import cn.hutool.captcha.LineCaptcha;

//验证码工具
public class CaptchaUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaUtil.class);

    @Value("${captcha.width:250}")
    private Integer width;

    @Value("${captcha.height:100}")
    private Integer height;

    //字母个数
    @Value("${captcha.numCount:5}")
    private Integer numCount;

    //干扰线数量
    @Value("${captcha.lineCount:5}")
    private Integer lineCount;

    //有效时间
    @Value("${captcha.validTime:300}")
    private Integer validTime;

    //验证码保存名称
    @Value("${captcha.name:captcha}")
    private String name;

    @Autowired
    private ICaptchaStore store;

    public String generate() {
        return generate("");
    }

    private String getKey(String key, String code) {
        if (StrUtil.isEmpty(key)) {
            return String.format("%s:ip:%s", name, code);
        }
        return String.format("%s:%s:%s", name, key, code);
    }

    /**
     * 生成验证码
     * @param key 自定义名称
     * @return
     */
    public String generate(String key) {
        LineCaptcha line = cn.hutool.captcha.CaptchaUtil.createLineCaptcha(width, height);
        //保存验证码
        String code = line.getCode();
        LOGGER.debug("captcha:{}", code);
        store.save(getKey(key, code), validTime);
        return line.getImageBase64Data();
    }

    public Boolean verify(String code) {
        return verify(code, "");
    }

    /**
     * 验证码校验
     * @param code 验证码
     * @param key  自定义名称
     * @return
     */
    public Boolean verify(String code, String key) {
        boolean result = store.verify(getKey(key, code));
        store.remove(getKey(key, code));
        return result;
    }
}
